<template>
    <div class="page">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="3">
                                    <h5>员工管理</h5>
                                </el-col>
                                <el-col :span="2" :offset="7">
                                    <el-button size="medium" type="warning" style="background: rgba(248,154,55,1);" @click="openCreateDialog">新增</el-button>
                                </el-col>
                                <el-col :span="6">
                                    <div class="block">
                                        <el-date-picker size="medium" v-model="queryParams.created_at" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                                        </el-date-picker>
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <el-input size="medium" placeholder="请输入员工姓名" v-model="queryParams.name" class="input-with-select">
                                        <el-button size="medium" slot="append" icon="el-icon-search" @click="search()"></el-button>
                                    </el-input>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="24" :xs="24" :sm="24" :lg="24">
                                    <el-table :data="staffData.data" style="width: 100%" v-loading="listLoading" @row-click="rowClick">
                                        <el-table-column
                                            prop="name"
                                            label="员工姓名">
                                        </el-table-column>
                                        <el-table-column
                                            prop="phone"
                                            label="手机号码">
                                        </el-table-column>
                                        <el-table-column
                                            prop="service_name"
                                            label="归属站点">
                                        </el-table-column>
                                        <el-table-column
                                            prop="created_at"
                                            label="注册时间">
                                        </el-table-column>
                                        <el-table-column
                                            label="权限">
                                            <template slot-scope="scope">{{ jurisdiction[scope.row.jurisdiction] }}</template>
                                        </el-table-column>
                                        <el-table-column
                                            label="实名认证">
                                            <template slot-scope="scope">{{ scope.row.is_authentication == '0' ? "未认证" : "已认证" }}</template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="delivery_num"
                                            label="入库（件）">
                                        </el-table-column>
                                        <el-table-column
                                            prop="send_num"
                                            label="派件（件）">
                                        </el-table-column>
                                    </el-table>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="panel-footer text-right">
                            <el-pagination @size-change="sizeChange" @current-change="currentChange"
                                           :current-page="queryParams.page"
                                           :page-sizes="[5, 10, 20, 50]"
                                           :page-size="queryParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="staffData.total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <!--员工详情对话框-->
        <el-dialog  :visible.sync="detailDialog" width="40%" :before-close="handleDetailClose">
            <span slot="title" class="dialog-header">
                <el-row>
                    <el-col :span="6">
                        <p style="font-size: 24px;">{{editParams.name}}</p>
                    </el-col>
                    <el-col :span="18">
                        <el-row v-if="editing">
                            <el-col :span="6" :offset="4" v-if="editBtn"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="editQuery">保存</el-button></el-col>
                            <el-col :span="6" v-if="editBtn"><el-button size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                            <el-col :span="6" v-if="editBtn"><el-button size="medium" type="primary"   @click="resetPassword">重置密码</el-button></el-col>

                        </el-row>
                        <el-row v-else>
                            <el-col :span="6" :offset="4" v-if="editBtn"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="enableEdit">编辑</el-button></el-col>
                            <el-col :span="6" v-if="editBtn"><el-button size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                            <el-col :span="6" v-if="editBtn"><el-button size="medium" type="primary"   @click="resetPassword">重置密码</el-button></el-col>

                        </el-row>
                    </el-col>
                </el-row>
                <el-row>
                    <el-tabs v-model="tabName" @tab-click="tabClick">
                        <el-tab-pane label="员工信息" name="info">
                            <el-form ref="editForm"   label-width="120px" :model="editParams" :rules="editRule">
                                <el-form-item label="员工姓名：" prop="name">
                                     <el-input v-model="editParams.name" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="手机号码：" prop="phone">
                                    <el-input v-model="editParams.phone" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="实名认证：" class="ID-Card">
                                    <img width="150" :src=" URL_HOST + editParams.heads_path" alt="">
                                    <img width="150" :src=" URL_HOST + editParams.tails_path" alt="">
                                </el-form-item>
                                <el-form-item label="工号：">
                                    <p>{{editParams.work_number}}</p>
                                </el-form-item>
                                <el-form-item label="注册时间：">
                                    <p>{{editParams.created_at}}</p>
                                </el-form-item>
                                <el-form-item label="归属站点：">
                                    <p>{{editParams.service_name}}</p>
                                </el-form-item>
                                <el-form-item label="权限：" prop="jurisdiction">
                                    <el-radio-group :disabled="!editing" v-model="editParams.jurisdiction">
                                        <el-radio  :label="0">入库</el-radio>
                                        <el-radio  :label="1">派送</el-radio>
                                        <el-radio  :label="2">入库、派送</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="入库佣金：" prop="delivery_commission">
                                     <el-input v-model="editParams.delivery_commission" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="派件佣金：" prop="send_commission">
                                     <el-input v-model="editParams.send_commission" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="收入：">
                                    <p>{{editParams.income}}元</p>
                                </el-form-item>
                                <el-form-item label="入库：">
                                    <p>{{editParams.delivery_num}}</p>
                                </el-form-item>
                                <el-form-item label="派件：">
                                    <p>{{editParams.send_num}}</p>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="操作日志" name="log">
                            <div style="min-height: 300px;">
                               <el-table :data="logData.data" style="width: 100%" >
                                    <el-table-column prop="created_at">
                                    </el-table-column>
                                    <el-table-column >
                                        <template slot-scope="scope">
                                            <el-row>
                                                {{scope.row.name}}{{scope.row.operation}}
                                            </el-row>
                                            <el-row v-if="scope.row.history!=null&&scope.row.actuality!=null">
                                                <p>修改前：<br><span v-for="(item,index) in scope.row.history">{{index}}:{{item}}<br></span></p>
                                                <p>修改后：<br><span v-for="(item,index) in scope.row.actuality">{{index}}:{{item}}<br></span></p>
                                            </el-row>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <el-pagination @size-change="logSizeChange" @current-change="logCurrentChange"
                                           :current-page="queryLogParams.page"
                                           :page-sizes="[5,10, 20, 50]"
                                           :page-size="queryLogParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="logData.total">
                            </el-pagination>
                        </el-tab-pane>
                    </el-tabs>
                </el-row>
            </span>
        </el-dialog>
        <el-dialog title="新增员工"  :visible.sync="createDialog"  width="40%" :before-close="handleCreateClose">
            <el-form ref="createForm" :rules="createRule" label-width="80px" :model="createParams">
                <el-form-item label="员工名称" prop="name">
                    <el-input v-model="createParams.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="createParams.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="createParams.password" minlength="6" maxlength="18"></el-input>
                </el-form-item>
                <el-form-item label="权限" prop="jurisdiction">
                    <el-radio-group v-model="createParams.jurisdiction">
                        <el-radio :label="0">入库</el-radio>
                        <el-radio :label="1">派送</el-radio>
                        <el-radio :label="2">入库、派送</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" style="background: rgba(248,154,55,1);" @click="createQuery">新增</el-button>
                    <el-button @click="handleCreateClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import api from '../apis'
    import Vue from 'vue';
    export default {
        name: "Staff",
        data(){
            let checkMobile = (rule, value, callback) => {
                let phone=/^[1][3,4,5,7,8][0-9]{9}$/;
                if (!phone.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                } else {
                    callback();
                }
            };
            return {
                //是否开启修改
                editing:false,
                //列表加载开关
                listLoading:false,
                //员工列表数据
                staffData:{
                    data: [],
                    total: 0,
                },
                //日志数据
                logData:{
                    data:[],
                    total:0,
                },
                //详情对话框
                detailDialog:false,
                //新增对话框
                createDialog:false,
                // 列表请求参数
                queryParams: {
                    page: 1,
                    paginate: 10,
                    name:'',
                    created_at:'',
                },
                //新增请求参数
                createParams:{
                    name:'',
                    phone:'',
                    password:'',
                    jurisdiction:'',
                },
                //日志请求参数
                queryLogParams:{
                    page:1,
                    paginate:5,
                    type:0,
                    uid:'',
                },
                //详情数据
                editParams:{

                },
                //编辑对话框按钮显示隐藏状态
                editBtn:true,
                //默认标签页
                tabName:'info',
                //权限数组
                jurisdiction:[
                    '入库',
                    '派件',
                    '入库、派件'
                ],
                editRule:{
                    // phone: [
                    //     { required: true, message: '请输入手机号码', trigger: 'blur' },
                    //     {validator: checkMobile, trigger: 'blur'}
                    // ],
                    name: [
                        { required: true, message: '请输入员工名称', trigger: 'blur' },
                    ],
                    // delivery_commission:[
                    //     { required: true, message: '请输入入库佣金', trigger: 'blur' },
                    // ],
                    // send_commission:[
                    //     { required: true, message: '请输入派件佣金', trigger: 'blur' },
                    // ],
                    // jurisdiction:[
                    //     { required: true, message: '请选择权限', trigger: 'blur' },
                    // ],
                },
                createRule:{
                    name: [
                        { required: true, message: '请输入员工名称', trigger: 'blur' },
                    ],
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                    ],
                    jurisdiction:[
                        { required: true, message: '请选择权限', trigger: 'blur' },
                    ],
                }
            }
        },
        methods:{
            /**
             *请求员工数据
             */
            queryStaff()
            {
                this.listLoading = true;
                api.staff.fetch(this.queryParams).then(response=>{
                    this.staffData = response.data;
                    this.listLoading = false;
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                });
            },

            fetchById(id)
            {
                api.staff.fetchById(id).then(response=>{
                    this.editParams = response.data.data;
                    if(this.detailData.heads_path == 'null'|| typeof(this.detailData.heads_path) =='unfinded'){
                        Vue.set(this.detailData,'heads_path','');
                    }
                    if(this.detailData.tails_path=='null'||typeof(this.detailData.tails_path) =='unfinded'){
                        Vue.set(this.detailData,'tails_path','');
                    }
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                });
            },
            /**
             * 操作日志请求
             */
            fetchLogs()
            {
                api.log.fetch(this.queryLogParams).then(response=>{
                    this.logData = response.data;
                    for(let i in this.logData.data){
                        if(this.logData.data[i].actuality!=null){
                            this.logData.data[i].actuality = JSON.parse(this.logData.data[i].actuality);
                        }
                        if(this.logData.data[i].history!=null){
                            this.logData.data[i].history = JSON.parse(this.logData.data[i].history);
                        }
                    }
                }).catch(errors=>{
                    this.$message.error('请求失败，'+response.data.resultCode);
                })
            },
            /**
             * 跳转到最后一页
             */
            jumpToLastPage () {
                let last = Math.ceil(this.staffData.total / this.queryParams.paginate);
                if (this.queryParams.page < last) {
                    this.queryParams.page = last;
                }
                this.queryStaff();
            },
            /**
             * 改变每页数量的时候请求列表
             * @param size
             */
            sizeChange(size){
                this.queryParams.paginate = size;
                this.queryStaff();
            },
            /**
             * 日志列表每页数量的时候
             */
            logSizeChange(size){
                this.queryLogParams.paginate = size;
                this.fetchLogs();
            },
            /**
             * 改变当前页的时候请求列表
             * @param index
             */
            currentChange(index){
                this.queryParams.page = index;
                this.queryStaff();
            },
            /**
             * 日志列表改变当前页的时候请求列表
             */
            logCurrentChange(index){
                this.queryLogParams.page = index;
                this.fetchLogs();
            },
            /**
             * 搜索按钮请求列表
             */
            search(){
                this.queryStaff();
            },
            /**
             * 列表行选中
             * @param row
             * @param event
             * @param column
             */
            rowClick(row, event, column){
                this.queryLogParams.uid = row.id;
                this.fetchById(row.id);
                this.detailDialog = true;
                this.fetchLogs();
            },
            /**
             * 修改请求
             */
            editQuery(){
                this.$refs['editForm'].validate((valid) =>{
                    if(valid){
                        api.staff.update(this.editParams.id,this.editParams).then(response=>{
                            for (let i in this.staffData.data){
                                if(this.staffData.data[i].id==this.editParams.id){
                                    Vue.set(this.staffData.data, i, response.data.data);
                                    break;
                                }
                            }
                            this.handleDetailClose();
                            this.$message.success('修改成功');
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 新增请求
             */
            createQuery(){
                this.$refs['createForm'].validate((valid) =>{
                    if(valid){
                        api.staff.create(this.createParams).then(response=>{
                            this.$message.success('新增成功');
                            this.staffData.total += 1;
                            this.jumpToLastPage();
                            this.handleCreateClose();
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 删除请求
             */
            delQuery(){
                this.$confirm('确认删除用户？', '删除用户', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    api.staff.destroy(this.editParams.id).then(response=>{
                        this.queryStaff();
                        this.handleDetailClose();
                        this.$message.success('删除成功');
                    }).catch(errors=>{
                        this.$message.error(errors.response.data.resultMessage);
                    });
                }).catch(() => {

                });
            },
            /**
             * 修改密码请求
             */
            resetPassword(){
                this.$confirm('重置成功后，密码将改变为123456。', '是否要为该员工重置密码？', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    api.staff.resetPassword(this.editParams.id).then(response=>{
                        this.$message.success('重置成功');
                    }).catch(errors=>{
                        this.$message.error('请求失败，'+response.data.resultCode);
                    })
                }).catch(() => {

                });
            },
            /**
             * 详情对话框关闭
             */
            handleDetailClose()
            {
                this.detailDialog = false;
                this.editParams = {};
            },
            /**
             * 新增对话框关闭
             */
            handleCreateClose(){
                this.createDialog = false;
                this.createParams = {};
            },
            /**
             * 编辑对话框标签页切换
             */
            tabClick(tab, event)
            {
                if(tab.name=='info'){
                    this.editBtn = true;
                }else{
                    this.editBtn = false;
                }
            },
            /**
             * 修改对话框点击修改按钮
             */
            enableEdit(){
                this.editing = true;
            },
            /**
             * 打开新增对话框
             */
            openCreateDialog(){
                this.createDialog = true;
            }
        },
        mounted (){
            this.queryStaff();
        }
    }
</script>
<style lang="scss" scoped>
    /* 日历插件样式 */
    .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner {
        width: 100%;
    }
    .el-range-editor.is-active, .el-range-editor.is-active:hover {
        border-color: #e6a23c;
    }
    .el-radio+.el-radio {
        margin-left: 16px;
    }
    /* 模拟框中的form item */
    .el-form-item {
        margin-bottom: 20px;
    }
    .el-form-item__content {
        line-height: 30px;
    }
</style>
<style lang="scss">
    .el-date-table td.available:hover {
        color: #e6a23c;
    }
    .el-date-table td.today span {
        color: #e6a23c;
    }
    .el-date-table td.end-date span, .el-date-table td.start-date span,
    .el-date-table td.end-date span, .el-date-table td.start-date span {
        background-color: #e6a23c;
    }
    /* 搜索框样式 */
    .el-input.is-active .el-input__inner, .el-input__inner:focus {
        border-color: #e6a23c;
    }
    .ID-Card img{
        margin:5px;
    }
</style>
